package com.raysweather.android;

import java.io.InputStream;
import java.net.URL;
import java.util.Calendar;
import java.util.Timer;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;

public class POTD extends Activity {

	private Timer timer;
	private RaysWeather rw;
	private POTDList potdList = null;
	private int updateDelay = 15;
	private static POTD potd;
	Drawable d = null;
	private ProgressDialog pd;
	BroadcastReceiver bReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if(action.equalsIgnoreCase("update")){    
				update();
			}
		}
	};

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		potd = this;
		setContentView(R.layout.potd);
		registerReceiver(bReceiver, new IntentFilter("update"));
		rw = RaysWeather.getInstance();
		//		updateDelay = rw.getDelay();
		Log.e("DELAY", "POTD delay set to "+updateDelay);
		if(rw.getService() != null)
			update();

		//		potdList = rw.getService().getPotdList();
		//		((ImageView)findViewById(R.id.potd_image)).setImageDrawable(getPOTD());
		//		((TextView)findViewById(R.id.potd_text)).setText(potdList.getText());
		//		Log.e("POTD", potdList.getText());

		/* Start updater */
		timer = new Timer();
		//		timer.schedule(new TimerTask() {
		//			@Override
		//			public void run() {
		//				timerMethod();
		//			}
		//		}, 0, updateDelay*60*1000);

	}

	public static POTD getInstance(){
		return potd;
	}

	public void setDelay(int delay){
		updateDelay = delay;
		timer = new Timer();
		//		timer.schedule(new TimerTask() {
		//			@Override
		//			public void run() {
		//				timerMethod();
		//			}
		//		}, 0, updateDelay*60*1000);
		//		Log.e("DELAY", "POTD delay set to "+updateDelay);
	}

	private void timerMethod(){
		this.runOnUiThread(updater);
	}

	private Runnable updater = new Runnable() {

		public void run() {
			update();
		}

	};

	private void update(){
		Log.e("POTD", "update");
		if(rw.getService() != null){
			potdList = rw.getService().getPotdList();
			((ImageView)findViewById(R.id.potd_image)).setImageDrawable(rw.getService().getPOTD());
			if(potdList != null)
				((TextView)findViewById(R.id.potd_text)).setText(potdList.getText());

			if(rw.getDelay() != updateDelay){
				timer = new Timer();
				//			timer.schedule(new TimerTask() {
				//				@Override
				//				public void run() {
				//					timerMethod();
				//				}
				//			}, 0, updateDelay*60*1000);
			}
		}
	}

	private Drawable getPOTD(){
		final Calendar c = Calendar.getInstance();
		Drawable d = null;
		//		while(d==null){
		//			//			String mYear = ""+c.get(Calendar.YEAR);
		//			//			String mMonth = ""+(c.get(Calendar.MONTH)+1);
		//			//			if(mMonth.length() == 1) mMonth = "0"+mMonth;
		//			//			String mDay = ""+(c.get(Calendar.DAY_OF_MONTH));
		//			//			if(mDay.length() == 1) mDay = "0"+mDay;
		//			//			String currentDateTimeString = ""+mYear+mMonth+mDay;
		//			//			Log.e("DATE", currentDateTimeString);
		if(potdList != null){
			d = LoadImageFromWebOperations("http://student.cs.appstate.edu/mbl1/5800/20110421_g.gif");
//			pd = ProgressDialog.show(this, "Loading..", "Getting Image", true, false);
		    Thread thread = new Thread(getPOTD);
	        thread.start();
		}
		//			//			long wait = System.currentTimeMillis()+1000;
		//			//			while(System.currentTimeMillis() < wait){}
		//			//			c.add(Calendar.DATE, -1);
		//		}
		return d;
	}

	private Runnable getPOTD = new Runnable() {

		public void run() {

			while(d==null){
				d = LoadImageFromWebOperations("http://student.cs.appstate.edu/mbl1/5800/20110421_g.gif");
			}
			handler.sendEmptyMessage(0);
		}
		private Handler handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
//				pd.dismiss();
				((ImageView)findViewById(R.id.potd_image)).setImageDrawable(d);

			}
		};
	};



	private Drawable LoadImageFromWebOperations(String url)
	{
		try
		{
			InputStream is = (InputStream) new URL(url).getContent();
			Drawable d = Drawable.createFromStream(is, "src name");
			Log.e("POTD", ""+(d==null));
			return d;
		}catch (Exception e) {
			System.out.println("Exc="+e);
			Log.e("POTD", "error");
			return null;
		}
	}

	private BitmapDrawable adjustImageSize(Drawable d){
		// load the origial BitMap (500 x 500 px)
		Bitmap bitmapOrg = ((BitmapDrawable)d).getBitmap();

		int width = bitmapOrg.getWidth();
		int height = bitmapOrg.getHeight();
		int newWidth = 100;
		int newHeight = 100;

		// calculate the scale - in this case = 0.4f
		float scaleWidth = ((float) newWidth) / width;
		float scaleHeight = ((float) newHeight) / height;

		// createa matrix for the manipulation
		Matrix matrix = new Matrix();
		// resize the bit map
		matrix.postScale(scaleWidth, scaleHeight);
		// rotate the Bitmap
		matrix.postRotate(45);

		// recreate the new Bitmap
		Bitmap resizedBitmap = Bitmap.createBitmap(bitmapOrg, 0, 0,
				width, height, matrix, true);

		// make a Drawable from Bitmap to allow to set the BitMap
		// to the ImageView, ImageButton or what ever
		BitmapDrawable bmd = new BitmapDrawable(resizedBitmap);

		return bmd;
	}

}